package withouther.system.core.util;

import com.alibaba.fastjson.JSON;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import withouther.system.core.security.entity.UserInfo;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@UtilityClass
public class SecurityUtil {

    public static void write(HttpServletResponse response, Object o) throws IOException {
//        response.setContentType("text/html;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(JSON.toJSONString(o));
        out.flush();
        out.close();
    }
    /**
     * 获取Authentication
     */
    private Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * @Author 李号东
     * @Description 获取用户
     * @Date 11:29 2019-05-10
     **/
    public UserInfo getUser(){
        try {
            return (UserInfo) getAuthentication().getPrincipal();
        } catch (Exception e) {
            e.printStackTrace();
//            throw new PreBaseException("登录状态过期", HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }

    /**
     * 当前是否是超级管理员
     * @return
     */
    public boolean isAdmin() {
        UserInfo userInfo = getUser();
        return userInfo != null && "admin".equals(userInfo.getUsername());
    }
    public boolean isAdmin(Long userId) {
        return userId == 1;
    }
}
